package com.qianfeng.realms;

import com.qianfeng.entity.Employee;
import com.qianfeng.entity.Role;
import com.qianfeng.service.EducationService;
import com.qianfeng.service.EmployeeService;
import com.qianfeng.service.RoleService;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.AuthenticationInfo;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.authc.SimpleAuthenticationInfo;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.apache.shiro.util.ByteSource;
import org.springframework.beans.factory.annotation.Autowired;

import java.util.HashSet;
import java.util.Set;

public class CommonRealm extends AuthorizingRealm {
@Autowired
private EmployeeService employeeService;
@Autowired
private RoleService roleService;
    /**
     * 授权
     * @param principalCollection
     * @return
     */
    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principalCollection) {
        SimpleAuthorizationInfo info = new SimpleAuthorizationInfo();
        String name = principalCollection.getPrimaryPrincipal().toString();
        Employee employee = employeeService.getEmployeeByEmail(name);
        Set<String> roles = new HashSet<>();
        //根据角色id查询角色名称
        Role roleByRoleId = roleService.getRoleByRoleId(employee.getRoleId());
        roles.add(roleByRoleId.getRoleName());
        info.setRoles(roles);
        return info;
    }

    /**
     * 认证
     * @param authenticationToken
     * @return
     * @throws AuthenticationException
     */
    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authenticationToken) throws AuthenticationException {
        System.out.println("邮箱密码"+authenticationToken.toString());
        //获取用户名称
        String principal = authenticationToken.getPrincipal().toString();
        //根据用户名获取用户信息
        Employee employeeByEmail = employeeService.getEmployeeByEmail(principal);
        if(employeeByEmail==null){
            return null;
        }
        //获取盐值
        String salt = employeeByEmail.getSalt();
        //类型转换
        ByteSource bytes = ByteSource.Util.bytes(salt);
        //封装数据库中的用户名密码
        SimpleAuthenticationInfo simpleAuthenticationInfo = new SimpleAuthenticationInfo(employeeByEmail.getEmail(), employeeByEmail.getEmpPassword(), bytes, getName());
        return simpleAuthenticationInfo;
    }
}
